package com.aruba.bulethoothdemoapplication.utils.printer;

import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.aruba.bulethoothdemoapplication.utils.livedatabus.LiveDataBus;

import java.util.List;


/**
 * Created by xuqiwei on 19-12-13.
 */

public abstract class PrinterTool implements Handler.Callback {
    private BluetoothService bluetoothService;
    private List<PrintStuff> printStuffs;
    private int connectCount = 0;
    private static final int MAX_CONNECT_COUNT = 5;

    private PrinterToolListener listener;

    public PrinterTool(PrinterToolListener listener) {
        this.listener = listener;
    }

    public abstract String getAddress();


    public void start() {
        if (bluetoothService == null) {
            bluetoothService = new BluetoothService(new Handler(this));
        }
        connect();
    }

    public void setPrinter(List<PrintStuff> printStuffList) {
        this.printStuffs = printStuffList;
    }


    //    宽高加倍
    public void doubleTextSize() {
        bluetoothService.write(new byte[]{29, 33, (byte) 17});
    }

    //    取消宽高加倍
    public void cancelDoubleTextSize() {
        bluetoothService.write(new byte[]{29, 33, (byte) 0});
    }

    private void print() {
        if (printStuffs == null || printStuffs.size() == 0) {
            Log.e("connect===", "没有可以打印的东西");
            destroy();
            return;
        }
        listener.onStartPrint();
        for (PrintStuff printStuff : printStuffs) {
            switch (printStuff.getPrintType()) {
                case ChangeSize:
                    doubleTextSize();
                    break;
                case ResetSize:
                    cancelDoubleTextSize();
                    break;
                case TextType:
//                    打印文字
                    bluetoothService.sendMessage(printStuff.getData(), "GBK");
                    break;
                case ImagePathType:
//                    打印图片
                    printImage(printStuff.getData());
                    break;
                case ImageBase64Type:
                    printImageWithBase64(printStuff.getData());
                    break;
            }
        }

        if (printStuffs != null) {
            printStuffs.clear();
        }

    }

    private void connect() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (bluetoothService == null) {
                    return;
                }
                bluetoothService.connect(bluetoothService.getDevByMac(getAddress()));
                LiveDataBus.getInstance().with(PrinterStatus.EVENT_KEY,PrinterStatus.class).setValue(new PrinterStatus("正在尝试第" + (connectCount+1) + "次连接"));

                if (connectCount == MAX_CONNECT_COUNT) {
                    LiveDataBus.getInstance().with(PrinterStatus.EVENT_KEY,PrinterStatus.class).setValue(new PrinterStatus("多次尝试连接失败,请重启蓝牙打印机"));
                    connectCount = 0;
                    return;
                }
                connectCount++;
            }
        }, 2000);

    }

//    public void configPrint(View view) {
//
//    }


    @Override
    public boolean handleMessage(Message message) {
        switch (message.what) {
            case BluetoothService.MESSAGE_STATE_CHANGE:
                switch (message.arg1) {
                    case BluetoothService.STATE_CONNECTED:
                        LiveDataBus.getInstance().with(PrinterStatus.EVENT_KEY,PrinterStatus.class).setValue(new PrinterStatus("连接成功，正在打印中..."));
                        connectCount = 0;
                        print();
                        break;
                    case BluetoothService.STATE_CONNECTING://正在连接

                        break;
                    case BluetoothService.STATE_LISTEN://监听连接的到来
                    case BluetoothService.STATE_NONE:

                        break;
                }
                break;
            case BluetoothService.MESSAGE_CONNECTION_LOST:
//                蓝牙已断开连接
                LiveDataBus.getInstance().with(PrinterStatus.EVENT_KEY,PrinterStatus.class).setValue(new PrinterStatus("蓝牙已断开连接"));
                connect();
                break;
            case BluetoothService.MESSAGE_UNABLE_CONNECT:
//                无法连接设备
                LiveDataBus.getInstance().with(PrinterStatus.EVENT_KEY,PrinterStatus.class).setValue(new PrinterStatus("无法连接设备,请重启打印机后重试"));
//                connect();
                break;
        }
        return false;
    }


    protected void destroy() {
        if (bluetoothService != null) {
            bluetoothService.stop();
        }
        bluetoothService = null;
    }

    private void printImage(String path) {
        byte[] sendData = null;
        PrintPic pg = new PrintPic();
        pg.initCanvas(600);
        pg.initPaint();
//        String path = Environment.getExternalStorageDirectory().getData()+ File.separator+"icon.png";
        pg.drawImage(0, 0, path);
        sendData = pg.printDraw();
        bluetoothService.write(sendData);   //打印byte流数据
    }

    private void printImageWithBase64(String base64Str) {
        Bitmap bitmap = PicPrintTool.base64ToBitmap(base64Str);
        byte[] sendData = null;
        PrintPic pg = new PrintPic();
        pg.initCanvas(600);
        pg.initPaint();
        pg.drawImageWithBitmap(0, 0, bitmap);
        sendData = pg.printDraw();
        bluetoothService.write(sendData);
    }

    public interface PrinterToolListener {
        void onStartPrint();
    }
}
